<template>
  <div class="evaluation">
    <div class="e-header">
      <div class="e-h-row">
        <div class="e-h-title">
          <i class="iconfont icon-shujuwajue"></i> 评测列表
        </div>
        <div class="fresh">
          <n-button round strong secondary type="info" size="small" @click="flushData">
            <i class="iconfont icon-htmal5icon23"></i>刷新
          </n-button>
        </div>
        <div class="state">
          <n-popselect v-model:value="currentStatus" :options="options" trigger="click">
            <n-button size="small" round>{{ currentStatus }}</n-button>
          </n-popselect>
        </div>
        <div class="e-h-search">
          <div class="search">
            <OjSearch class="search-input" placeholder="搜索题目ID" @search="(v) => {
              judgeParams.displayPid = v
              judgeParams.pageNum = 1
              $router.push({ query: judgeParams })
              getJudgeList()
            }"></OjSearch>
          </div>
          <div class="search">
            <OjSearch class="search-input" placeholder="搜索作者" @search="(v) => {
              judgeParams.username = v
              judgeParams.pageNum = 1
              $router.push({ query: judgeParams })
              getJudgeList()
            }"></OjSearch>
          </div>
        </div>
      </div>
    </div>
    <div class="e-body">
      <el-table class="table no-background" :data="judgeList.records" size="small" :row-class-name="getClassName"
        @row-dblclick="showEvaluationDetail">
        <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod" />
        <el-table-column prop="displayPid" label="题目ID">
          <template #default="scoped">
            <div class="problemTable-title" @click="handlerToQueation(scoped.row.pid)">
              {{ scoped.row.displayPid }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" min-width="130px">
          <template #default="scoped">
            <n-tag v-for="(item, index) in statusTags" :key="item.status" :type="item.type" strong
              v-show="scoped.row.status == item?.status" round size="small">
              {{ item.text }}
              <template #icon>
                <i :class="`iconfont ${item.icon}`"></i>
              </template>
            </n-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" align="center">
          <template #default="scoped">
            {{ scoped.row.score || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="time" label="运行时间" align="center">
          <template #default="scoped">
            {{ scoped.row.time || "--" }}ms
          </template>
        </el-table-column>
        <el-table-column prop="memory" label="运行内存" align="center">
          <template #default="scoped">
            {{ getmemory(scoped.row.memory, 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="length" label="代码长度" align="center">
          <template #default="scoped">
            {{ scoped.row.length || "--" }}B
          </template>
        </el-table-column>
        <el-table-column prop="language" label="语言" align="center">
          <template #default="scoped">
            <div class="problemTable-title" @click="showEvaluationDetail(scoped.row)">
              {{ scoped.row.language }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="judger" label="判题源" align="center"></el-table-column>
        <el-table-column prop="username" label="作者" align="center"></el-table-column>
        <el-table-column prop="submitTime" label="提交时间" align="center">
          <template #default="scoped">
            <el-tooltip :content="scoped.row.submitTime" placement="top">
              <div style="cursor: pointer;">{{ getDay(scoped.row.submitTime) || "--" }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="重新评测" align="center" v-if="$store.oj.premission.includes('web:front:toManage')">
          <template #default="scoped">
            <n-button size="tiny" type="info" strong @click="reSubmit(scoped.row.submitId)">
              <transition>
                <i class="iconfont icon-jiazai loading-icon" v-show="scoped.row.submitId === submitId"></i>
              </transition>
              重新测评
            </n-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="e-footer">
      <el-pagination class="pagination" :page-sizes="[20, 50, 100]" background small layout="prev, pager, next,sizes"
        :total="Number(judgeList.total)" v-model:current-page="judgeParams.pageNum"
        v-model:page-size="judgeParams.pageSize" @change="() => {
          $router.push({ query: judgeParams })
        }" />
    </div>
  </div>
</template>

<script>
import {
  getJudgeListAPI,
  reSubmitAPI,
  getJudgeDetailAPI,
} from "@/api/ojAPI/ojAPI"
import { wordsToStatus } from "@/utils/global.js"
import { ElMessage } from "element-plus"
import OjSearch from '@/components/common/ojSearch.vue'
// config
import { optionConfig, statusTags } from './config'
const arr = ["KB", "MB", "GB"]
export default {
  data() {
    return {
      judgeList: {
        records: [],
        total: 20,
      },
      statusTags: statusTags,
      judgeParams: {
        pageNum: parseInt(this.$route.query.pageNum) || 1,
        pageSize: parseInt(this.$route.query.pageSize) || 20,
        status: parseInt(this.$route.query.status) || 15,
        displayPid: this.$route.query.displayPid || "",
        username: this.$route.query.username || "",
      },
      options: optionConfig,
      currentStatus: "全部",
      timer: 0,
      reUpdatePro: {},
      submitId: -1,
      pid: '',
      username: ''
    }
  },
  mounted() {
    // this.$router.push({ query: this.judgeParams })
    this.getJudgeList()
  },
  methods: {
    async getJudgeList() {
      await getJudgeListAPI(this.judgeParams)
        .then((res) => {
          if (res.data.code === 200) {
            this.judgeList = res.data.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getDay(time) {
      const now = Date.now()
      var timer = Date.parse(time)
      const second = Number(((now - timer) / 1000).toFixed(0))
      if (second < 60) {
        return "刚刚"
      }
      const minute = Number((second / 60).toFixed(0))
      if (minute < 60) {
        return minute + '分钟前'
      }
      const hour = Number((minute / 60).toFixed(0))
      if (hour < 24) {
        return hour + '小时前'
      }
      const day = Number((hour / 24).toFixed(0))
      if (day < 31) {
        return day + '天前'
      }
      const mounth = Number((day / 30).toFixed(0))
      if (mounth < 12) {
        return mounth + '月前'
      }
      const year = Number((mounth / 12).toFixed(0))
      return year + '年前'
    },
    handlerToQueation(id) {
      this.$router.push({
        path: `bank/${id}`,
      })
    },
    getClassName(data) {
      const { row } = data
      if (row.status == 0 || row.status == 12) {
        return "success-row"
      } else if (row.status == 1 || row.status == 11 || row.status == 12) {
        return "info-row"
      } else if (row.status == 6 || row.status == 8) {
        return "warning-row"
      } else if (row.status == 5) {
        return "grey-row"
      }
      return "error-row"
    },
    flushData() {
      let now = Date.now()
      if (now - this.timer > 1000) {
        this.timer = now
        this.getJudgeList()
      }
      return
    },
    getmemory(val, index) {
      if (val == null) {
        return "--B"
      }
      if (val < 1024) {
        return val + arr[index]
      }
      index += 1
      val = Number((val / 1024).toFixed(2))
      return this.getmemory(val, index)
    },
    showEvaluationDetail(row) {
      if (this.submitId != -1) {
        return
      }
      if (row.status > 10) {
        return
      }
      this.$router.push({
        path: `/home/evaluation-detail/${row.submitId}`,
      })
    },
    async reSubmit(id) {
      if (id === this.submitId) {
        return
      }
      this.submitId = id
      await reSubmitAPI({
        submitId: id
      })
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
            this.getJudgeDetail(id)
          }
        })
        .catch((err) => {
          console.log("系统错误")
        })
    },
    handlerToProblem(id) {
      this.$router.push({
        path: `/home/bank/${id}`,
      })
    },
    async getJudgeDetail(id) {
      await getJudgeDetailAPI(id)
        .then((res) => {
          if (res.data.code === 200) {
            if (res.data.data.status > 10) {
              setTimeout(() => {
                this.getJudgeDetail(id)
              }, 2000)
              this.reUpdatePro = res.data.data
              for (var i = 0; i < this.judgeList.records.length; i++) {
                if (
                  this.judgeList.records[i].submitId ===
                  this.reUpdatePro.submitId
                ) {
                  this.judgeList.records[i] = this.reUpdatePro
                }
              }
              return
            }
            this.reUpdatePro = res.data.data
            for (var i = 0; i < this.judgeList.records.length; i++) {
              if (
                this.judgeList.records[i].submitId === this.reUpdatePro.submitId
              ) {
                this.judgeList.records[i] = this.reUpdatePro
              }
            }
            this.submitId = -1
          } else {
            this.submitId = -1
          }
        })
        .catch((err) => {
          ElMessage.error("系统错误")
        })
    },
    indexMethod(index) {
      return (
        (this.judgeParams.pageNum - 1) * this.judgeParams.pageSize + index + 1
      )
    },
  },
  computed: {},
  watch: {
    currentStatus: function (newval) {
      this.judgeParams.status = wordsToStatus(newval)
      this.judgeParams.pageNum = 1
      this.$router.push({ query: this.judgeParams })
      this.getJudgeList()
    },
    '$route.query': {
      deep: true,
      handler(newV) {
        Object.assign(this.judgeParams, {
          pageNum: parseInt(newV.pageNum),
          pageSize: parseInt(newV.pageSize),
          status: parseInt(newV.status),
          displayPid: newV.displayPid,
          username: newV.username,
        })
        this.getJudgeList()
      },
    }
  },
}
</script>

<style lang="less" scoped>
.evaluation {
  width: 95%;
  padding-top: 10px;
  margin: 0 auto;
  border-radius: 16px;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .e-header {
    width: 100%;
    height: 10%;

    .e-h-row {
      display: flex;
      justify-content: space-between;

      .e-h-title {
        font-size: 22px;
        font-weight: 600;
        color: #555;

        .iconfont {
          font-weight: normal;
          font-size: 24px;
        }
      }

      .fresh {
        margin: auto 0 auto auto;
        text-align: center;

        .iconfont {
          text-align: center;
        }
      }

      .state {
        margin: auto 0 auto 20px;
      }

      .e-h-search {
        width: 30%;
        display: flex;

        .search {
          width: 40%;
          display: flex;
          margin: auto;

          .search-input {
            width: 100%;
            margin: auto 0 0 0;
          }
        }
      }
    }
  }

  .e-body {
    height: 80%;
    width: 98%;
    margin: 10px auto;

    .table {
      height: 75vh;
    }

    .table-pid {
      &:hover {
        color: rgb(58, 159, 85);
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }

  .e-footer {
    min-height: 40px;
    line-height: 40px;
    width: 98%;
    display: flex;
    justify-content: center;
    margin: auto 0;
  }
}

.loading-icon {
  transition: 0.5s;
  animation: rotatee 2s linear infinite;
}

@keyframes rotatee {
  0% {
    transform: rotate(0);
  }

  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(270deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.v-enter-active {
  transition: opacity 0.2s ease;
}

.v-leave-active {
  display: none;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.problemTable-title {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    color: rgb(46, 187, 84);
    cursor: pointer;
    text-decoration: underline;
  }
}
</style>
